﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using HK2009.Common;
using HK2009.BusinessFacade;
using HK2009.BusinessFacadeHandler;
using HK2009.EntityQuery;
using System.Data.SqlClient;
using System.Text;
using System.Collections.Generic;
using System.Threading;

public partial class BookingNote_BookingNoteUpdate : BasePage
{
    IRolePurviewHandler userManage = new RolePurviewHandler();
    ISyClientHandler clientManage = new SyClientHandler();
    ISyMarketHandler markManage = new SyMarketHandler();
    ISyPlaceHandler placeManage = new SyPlaceHandler();
    ISyDestinationHandler destManage = new SyDestinationHandler();
    IBNBookingNoteHandler bookingNoteManage = new BNBookingNoteHandler();
    ISystemHandler systemManage = new SystemHandler();

    IBNBookingHandler bookingManage = new BNBookingHandler();
    DataBase db = new DataBase();

    private static string clientName = string.Empty;
    private static int num = -1;
    private static string bnDetailID = string.Empty;
    private static bool isUpdate = false;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session["UserID"] != null)
            {
                ISystemHandler sysManage = new SystemHandler();
                string strPermission = sysManage.GetLoginUserPermissions();
                if (!(strPermission.Contains("1055")))
                {
                    Response.Redirect("~/NotPurview.aspx");
                    return;
                }
            }
            ddlShipper.Focus();
            ViewState["OrderBy"] = "PKID";
            ViewState["Accending"] = "desc";
            FillDDl();
            dataBind();
        }
    }

    private void dataBind()
    {
        if (Request["BookingNoteID"] != null)
        {
            BN_BookingNoteQuery bnQuery = bookingNoteManage.GetBookingNoteByPKID(int.Parse(Request["BookingNoteID"]));
            if (bnQuery != null)
            {
                ddlShipper.SelectedValue = bnQuery.ShipperID.ToString();
                BindShipperLM(bnQuery.ShipperID);
                ddlShipperLM.Enabled = true;
                ddlShipperLM.SelectedValue = bnQuery.ShipperLMID.ToString();
                txtInvoiceNO.Text = bnQuery.InvoiceNO;
                txtPcNO.Text = bnQuery.PcNO;
                txtWinStart.Text = bnQuery.WinStart != System.DateTime.MinValue ? bnQuery.WinStart.ToString("yyyy-MM-dd") : string.Empty;

              
                txtWinClose.Text = bnQuery.WinClose != System.DateTime.MinValue ? bnQuery.WinClose.ToString("yyyy-MM-dd") : string.Empty;

                  if (bnQuery.WinClose != System.DateTime.MinValue)
                {
                    if (bnQuery.WinClose.ToString("yyyy-MM-dd HH:mm").Substring(11, 5) != "00:00")
                    {
                        txtWinCloseH.Text = bnQuery.WinClose.ToString("yyyy-MM-dd HH:mm").Substring(11, 5).Remove(2, 1).Trim();
                    }
                }

                txtWinLastClose.Text = bnQuery.WinLastClose != System.DateTime.MinValue ? bnQuery.WinLastClose.ToString("yyyy-MM-dd") : string.Empty;

                if (bnQuery.WinLastClose != System.DateTime.MinValue)
                {
                    if (bnQuery.WinLastClose.ToString("yyyy-MM-dd HH:mm").Substring(11, 5) != "00:00")
                    {
                        txtWinLastCloseH.Text = bnQuery.WinLastClose.ToString("yyyy-MM-dd HH:mm").Substring(11, 5).Remove(2, 1).Trim();
                    }
                }

                ddlCustomer.SelectedValue = bnQuery.CustomerID.ToString();
                ddlMarket.SelectedValue = bnQuery.MarketID.ToString();
                ddlDestination.SelectedValue = bnQuery.DestinationID.ToString();
                ddlCarrierForwar.SelectedValue = bnQuery.CarrierForwar.ToString();
                txtSICutOFFDate.Text = bnQuery.SICutOFFDate != System.DateTime.MinValue ? bnQuery.SICutOFFDate.ToString("yyyy-MM-dd") : string.Empty;

                if (bnQuery.SICutOFFDate != System.DateTime.MinValue)
                {
                    if (bnQuery.SICutOFFDate.ToString("yyyy-MM-dd HH:mm").Substring(11, 5) != "00:00")
                    {
                        txtSICutOFFDateH.Text = bnQuery.SICutOFFDate.ToString("yyyy-MM-dd HH:mm").Substring(11, 5).Remove(2, 1).Trim();
                    }
                }
                
                txtCPO.Text = bnQuery.CPO.ToString();
                txtRemark.Text = bnQuery.Remark.ToString();
                txtBillDate.Text = bnQuery.BillDate !=System.DateTime.MinValue? bnQuery.BillDate.ToString("yyyy-MM-dd"):string.Empty;
                txtVVD.Text = bnQuery.VV;

                txtJobNumber.Text = bnQuery.JobNumber;
                txtSourceCode.Text = bnQuery.SourceCode;
            }

            SqlParameter[] parms = new SqlParameter[1];
            parms[0] = new SqlParameter("@BookingNoteID", Request["BookingNoteID"]);
            string sqlStr = "select * from BN_BookingNoteDtl where BookingNoteID=@BookingNoteID ";

            DataTable dtB = bookingNoteManage.GetBookingNoteDetailList(sqlStr, parms);
            if (dtB != null && dtB.Rows.Count > 0)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("RowNum");
                dt.Columns.Add("BookingNoteDtlID");
                dt.Columns.Add("ConfirmNO");
                dt.Columns.Add("VendorID");
                dt.Columns.Add("WhouseID");
                dt.Columns.Add("PlaceID");
                dt.Columns.Add("SONO");
                dt.Columns.Add("FCLLCL");
                dt.Columns.Add("HKPRC");
                dt.Columns.Add("JobDate");
                dt.Columns.Add("DeliveryDate");
                dt.Columns.Add("ItemNO");
                dt.Columns.Add("PCS");
                dt.Columns.Add("CTN");
                dt.Columns.Add("GrossWT");
                dt.Columns.Add("VOL");
                dt.Columns.Add("ContainerNO");
                dt.Columns.Add("SealNO");
                dt.Columns.Add("VV");
                dt.Columns.Add("PNNO");
                dt.Columns.Add("BuyerPONO");
                dt.Columns.Add("PCNO");
                dt.Columns.Add("CargoReadyDate");
                dt.Columns.Add("TruckCO");
                dt.Columns.Add("Remark");
                dt.Columns.Add("VendorName");
                dt.Columns.Add("WhouseName");
                dt.Columns.Add("PlaceName");
                dt.Columns.Add("BespokeDate");
                dt.Columns.Add("PKID");
                dt.Columns.Add("VendorLinkMan");
                dt.Columns.Add("VendorLinkManName");
                dt.Columns.Add("SourceCode");
                dt.Columns.Add("AppointmentNO");

                for (int i = 0; i < dtB.Rows.Count; i++)
                {
                    dt.Rows.Add(new string[] {
                Convert.ToString(i+1),
                dtB.Rows[i]["PKID"].ToString(),
                dtB.Rows[i]["ConfirmNO"].ToString(),
                dtB.Rows[i]["VendorID"].ToString(),
                dtB.Rows[i]["WhouseID"].ToString(),
                dtB.Rows[i]["PlaceID"].ToString(),
                dtB.Rows[i]["SONO"].ToString(),               
                dtB.Rows[i]["FCLLCL"].ToString(),
                dtB.Rows[i]["HKPRC"].ToString(),
                dtB.Rows[i]["JobDate"] !=System.DBNull.Value ? DateTime.Parse(dtB.Rows[i]["JobDate"].ToString()).ToString("yyyy-MM-dd HH:mm"):string.Empty,
                
                dtB.Rows[i]["DeliveryDate"] !=System.DBNull.Value ? DateTime.Parse(dtB.Rows[i]["DeliveryDate"].ToString()).ToString("yyyy-MM-dd"):string.Empty,
                dtB.Rows[i]["ItemNO"].ToString(),
                dtB.Rows[i]["PCS"].ToString(),
                dtB.Rows[i]["CTN"].ToString(),
                dtB.Rows[i]["GrossWT"].ToString(),
                dtB.Rows[i]["VOL"].ToString(),
                dtB.Rows[i]["ContainerNO"].ToString(), 
              
                dtB.Rows[i]["SealNO"].ToString(),
                dtB.Rows[i]["VV"].ToString(),
                dtB.Rows[i]["PNNO"].ToString(),   

                dtB.Rows[i]["BuyerPONO"].ToString(),
                dtB.Rows[i]["PCNO"].ToString(),
                dtB.Rows[i]["CargoReadyDate"] !=System.DBNull.Value ? DateTime.Parse(dtB.Rows[i]["CargoReadyDate"].ToString()).ToString("yyyy-MM-dd"):string.Empty, 
                dtB.Rows[i]["TruckCO"].ToString(),
                dtB.Rows[i]["Remark"].ToString(),               
                GetClientName(int.Parse(dtB.Rows[i]["VendorID"].ToString())),
                GetClientName(int.Parse(dtB.Rows[i]["WhouseID"].ToString())),
                "",
                dtB.Rows[i]["BespokeDate"] !=System.DBNull.Value ? DateTime.Parse(dtB.Rows[i]["BespokeDate"].ToString()).ToString("yyyy-MM-dd"):string.Empty,
                dtB.Rows[i]["PKID"].ToString(),
                dtB.Rows[i]["VendorLinkMan"].ToString() !=string.Empty ? dtB.Rows[i]["VendorLinkMan"].ToString():"0",
                GetClientLinkMan(dtB.Rows[i]["VendorLinkMan"].ToString() !=string.Empty ? int.Parse(dtB.Rows[i]["VendorLinkMan"].ToString()):0),
                dtB.Rows[i]["SourceCode"].ToString(),
                dtB.Rows[i]["Appointament"].ToString()
                   });
                }

                ViewState["BookingNoteDetail"] = dt;
            }

          //  FillDDl();
            dataBindDetail();
        }
    }

    private void dataBindDetail()
    {

        DataTable dtB= new DataTable();
        if (ViewState["BookingNoteDetail"] != null)
        {
            divEntrust.Visible = true;
            dtB = (DataTable)ViewState["BookingNoteDetail"];

            DataView view = dtB.DefaultView;
            gvBookNoteDetailList.DataSource = view;
            gvBookNoteDetailList.DataBind();
            if (dtB != null && dtB.Rows.Count > 0)
            {
                lblTotal.Text = dtB.Rows.Count.ToString();
            }
            else
            {
                lblTotal.Text = "0";
            }
        }
        else
        {
            divEntrust.Visible = false;
        }       
    }

    public string GetClient(object id)
    {
        return systemManage.GetClient(id);
    }

    public string GetClientLinkMan(int cLinkMan)
    {
        string name = string.Empty;
        SqlParameter[] parms = new SqlParameter[1];
        parms[0] = new SqlParameter("@PKID", cLinkMan.ToString());
        string sqlStr = "select * from Sy_ClientLinkMan where PKID =@PKID";
        DataTable dt = clientManage.GetClientLinkManList(sqlStr, parms);
        if (dt != null && dt.Rows.Count > 0)
        {
            name = dt.Rows[0]["LinkMan"].ToString();
        }
        return name;
    }


    #region FillDll
    private void FillDDl()
    {
        //绑定托运人
        DataTable dt = clientManage.GetClientListByTypeID(int.Parse(Enums.CT.TYR.ToString("d")));
        ddlShipper.DataSource = dt;

        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            ddlShipper.DataTextField = "ENGShortName";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            ddlShipper.DataTextField = "HKShortName";
        }
        else
        {
            ddlShipper.DataTextField = "CNShortName";
        }
        ddlShipper.DataValueField = "PKID";
        ddlShipper.DataBind();
        ddlShipper.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));

        //客户客人
        dt = clientManage.GetClientListByTypeID(int.Parse(Enums.CT.KHKR.ToString("d")));
        ddlCustomer.DataSource = dt;
        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            ddlCustomer.DataTextField = "ENGShortName";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            ddlCustomer.DataTextField = "HKShortName";
        }
        else
        {
            ddlCustomer.DataTextField = "CNShortName";
        }
        ddlCustomer.DataValueField = "PKID";
        ddlCustomer.DataBind();
        ddlCustomer.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));

        //市场
        dt = markManage.GetList();
        ddlMarket.DataSource = dt;
        ddlMarket.DataTextField = "CNName";
        ddlMarket.DataValueField = "PKID";
        ddlMarket.DataBind();
        ddlMarket.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));

        //目的地
        dt = destManage.GetList();
        ddlDestination.DataSource = dt;
        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            ddlDestination.DataTextField = "ENGName";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            ddlDestination.DataTextField = "HKName";
        }
        else
        {
            ddlDestination.DataTextField = "CNName";
        }
        ddlDestination.DataValueField = "PKID";
        ddlDestination.DataBind();
        ddlDestination.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));


        //工厂
        dt = clientManage.GetClientListByTypeID(int.Parse(Enums.CT.GC.ToString("d")));
        //ddlVendor.DataSource = dt;
        //if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        //{
        //    ddlVendor.DataTextField = "ENGShortName";
        //}
        ddlVendor.Items.Add(new ListItem(Resources.Messages.PleaseSelect, "0"));
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            ListItem item = new ListItem();
            if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
            {
                // ddlVendor.DataTextField = "HKShortName";
                item.Text = dt.Rows[i]["ENGShortName"].ToString() + "/" + dt.Rows[i]["HKShortName"].ToString();
            }
            else
            {
                item.Text = dt.Rows[i]["ENGShortName"].ToString() + "/" + dt.Rows[i]["CNShortName"].ToString();
                //ddlVendor.DataTextField = "CNShortName";
            }
            item.Value = dt.Rows[i]["PKID"].ToString();
            // ddlVendor.DataValueField = "PKID";
            ddlVendor.Items.Add(item);
        }
        // ddlVendor.DataBind();
        // ddlVendor.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));

        //仓库
        dt = clientManage.GetClientListByTypeID(int.Parse(Enums.CT.CK.ToString("d")));
        ddlWhouse.DataSource = dt;
        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            ddlWhouse.DataTextField = "ENGShortName";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            ddlWhouse.DataTextField = "HKShortName";
        }
        else
        {
            ddlWhouse.DataTextField = "CNShortName";
        }
        ddlWhouse.DataValueField = "PKID";
        ddlWhouse.DataBind();
        ddlWhouse.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));


        //船公司/货代
        SqlParameter[] parms = new SqlParameter[3];
        parms[0] = new SqlParameter("@TypeID", Enums.CT.CGS.ToString("d"));
        parms[1] = new SqlParameter("@Status", "1");
        parms[2] = new SqlParameter("@TypeID2", Enums.CT.HD.ToString("d"));
        string sqlStr = "select * from Sy_Client where PKID in(select ClientID from Sy_ClientType where SyCodeID=@TypeID OR SyCodeID=@TypeID2) and Status=@Status";

        dt = clientManage.GetClientList(sqlStr, parms);
        ddlCarrierForwar.DataSource = dt;
        if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("en"))
        {
            ddlCarrierForwar.DataTextField = "ENGShortName";
        }
        else if (Thread.CurrentThread.CurrentUICulture.ToString().ToLower().Equals("zh-hk"))
        {
            ddlCarrierForwar.DataTextField = "HKShortName";
        }
        else
        {
            ddlCarrierForwar.DataTextField = "CNShortName";
        }
        ddlCarrierForwar.DataValueField = "PKID";
        ddlCarrierForwar.DataBind();
        ddlCarrierForwar.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));
    }
    #endregion


    protected void lbtnGo_Click(object sender, EventArgs e)
    {
        TextBox txtPages = ((TextBox)gvBookNoteDetailList.BottomPagerRow.FindControl("txtPages"));
        try
        {
            int i = Convert.ToInt32(txtPages.Text) - 1;
            if (i >= 0 && i < gvBookNoteDetailList.PageCount)
            {
                this.gvBookNoteDetailList.PageIndex = i;
                //数据绑定
                dataBind();
            }
            else
            {
                Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);
                return;
            }
        }
        catch
        {
            Jscript.AlertInAjax(Resources.Messages.WrongPageNumInput, UpdatePanel1);
           

        }
    }
    protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
    {
        gvBookNoteDetailList.PageSize = int.Parse(ddlPages.SelectedValue);
        dataBindDetail();
    }

    protected void gvBookNoteDetailList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvBookNoteDetailList.PageIndex = e.NewPageIndex;
        dataBindDetail();
    }
    
    protected void gvBookNoteDetailList_RowDataBound(object sender, GridViewRowEventArgs e)
    {

    }
    protected void lbtnAddDetailBookNote_Click(object sender, EventArgs e)
    {
         BN_BookingNoteQuery bnQuery = bookingNoteManage.GetBookingNoteByPKID(int.Parse(Request["BookingNoteID"]));
         if (bnQuery != null)
         {
             //if (bnQuery.Status == int.Parse(Enums.BookingNoteStatus.CHECK.ToString("d")))
             //{
             //    Jscript.AlertInAjax(Resources.Messages.BookingnoteNotEdit, UpdatePanel1);
             //    return;
             //}
                        
             bnDetailID = string.Empty;
         }
    }


    protected void btnSub_Click(object sender, EventArgs e)
    {
        //BN_BookingNoteQuery bnQuery = bookingNoteManage.GetBookingNoteByPKID(int.Parse(Request["BookingNoteID"]));
        //if (bnQuery != null)
        //{
        //    //if (bnQuery.Status == int.Parse(Enums.BookingNoteStatus.CHECK.ToString("d")))
        //    //{
        //    //    Jscript.AlertInAjax(Resources.Messages.BookingnoteNotEdit, UpdatePanel1);
        //    //    return;
        //    //}
        //}

        isUpdate = true;
        DataTable dt = new DataTable();

        string vendorName = string.Empty;
        string whouseName = string.Empty;
        string placeName = string.Empty;
        string vendorLinkManName = string.Empty;

        if (ddlVendor.SelectedValue != "0")
        {
            vendorName = ddlVendor.SelectedItem.Text;
        }
        if (ddlWhouse.SelectedValue != "0")
        {
            whouseName = ddlWhouse.SelectedItem.Text;
        }

        if (ddlVendorLM.SelectedValue != "0" && ddlVendorLM.SelectedValue !=string.Empty)
        {
            vendorLinkManName = ddlVendorLM.SelectedItem.Text;
        }

        if (ViewState["BookingNoteDetail"] == null)//新建第一条数据
        {
            dt.Columns.Add("RowNum");
            dt.Columns.Add("BookingNoteDtlID");
            dt.Columns.Add("ConfirmNO");
            dt.Columns.Add("VendorID");
            dt.Columns.Add("WhouseID");
            dt.Columns.Add("PlaceID");
            dt.Columns.Add("SONO");
            dt.Columns.Add("FCLLCL");
            dt.Columns.Add("HKPRC");
            dt.Columns.Add("JobDate");
            dt.Columns.Add("DeliveryDate");
            dt.Columns.Add("ItemNO");
            dt.Columns.Add("PCS");
            dt.Columns.Add("CTN");
            dt.Columns.Add("GrossWT");
            dt.Columns.Add("VOL");
            dt.Columns.Add("ContainerNO");
            dt.Columns.Add("SealNO");
            dt.Columns.Add("VV");
            dt.Columns.Add("PNNO");
            dt.Columns.Add("BuyerPONO");
            dt.Columns.Add("PCNO");
            dt.Columns.Add("CargoReadyDate");
            dt.Columns.Add("TruckCO");
            dt.Columns.Add("Remark");
            dt.Columns.Add("VendorName");
            dt.Columns.Add("WhouseName");
            dt.Columns.Add("PlaceName");
            dt.Columns.Add("BespokeDate");
            dt.Columns.Add("PKID");
            dt.Columns.Add("VendorLinkMan");
            dt.Columns.Add("VendorLinkManName");
            dt.Columns.Add("SourceCode");
            dt.Columns.Add("AppointmentNO");
            dt.Rows.Add(new string[] {
                "1",
                 "0",
                txtConfirmNo.Text.Trim(),
                ddlVendor.SelectedValue,
                ddlWhouse.SelectedValue,
                "0",
                txtSONO.Text.Trim(),               
                ddlFCLLCL.SelectedValue,
                ddlHKPRC.SelectedValue,
                txtJobDate.Text!=string.Empty?txtJobDate.Text.Trim() +HK2009.Common.StringUtil.GetTime(txtJobDateH.Text.Trim()):string.Empty,
                 System.DBNull.Value.ToString(),
                txtItemNO.Text.Trim(),
                txtPCS.Text.Trim() !=string.Empty?txtPCS.Text.Trim():"0",
                txtCTN.Text.Trim()!=string.Empty?txtCTN.Text.Trim():"0",
                txtGrossWT.Text.Trim()!=string.Empty ?txtGrossWT.Text.Trim():"0",
                txtVOL.Text.Trim() !=string.Empty ? txtVOL.Text.Trim() :"0",
                txtContainerNO.Text.Trim(),
                txtSealNO.Text.Trim(),
                string.Empty,
                txtPNNO.Text.Trim(),
                string.Empty,
                txtPCNOD.Text.Trim(),
                txtCargoReadyDate.Text.Trim(),
                string.Empty,
                txtRemarkD.Text.Trim(),
                vendorName,
                whouseName,
                placeName,
                System.DBNull.Value.ToString(),
                "0",
                ddlVendorLM.SelectedValue != string.Empty ?ddlVendorLM.SelectedValue:"0" ,
                vendorLinkManName,
                txtSourceCode.Text.Trim(),
                txtAppointmentNO.Text
            });
        }
        else if (num != -1)//更新缓存的其中一条数据
        {
            dt = (DataTable)ViewState["BookingNoteDetail"];
            

            dt.Rows[(num - 1)]["ConfirmNo"] = txtConfirmNo.Text;
            dt.Rows[(num - 1)]["VendorID"] = ddlVendor.SelectedValue;
            dt.Rows[(num - 1)]["WhouseID"] = ddlWhouse.SelectedValue;
            dt.Rows[(num - 1)]["PlaceID"] = "0";
            dt.Rows[(num - 1)]["SONO"] = txtSONO.Text;
            dt.Rows[(num - 1)]["FCLLCL"] = ddlFCLLCL.SelectedValue;
            dt.Rows[(num - 1)]["HKPRC"] = ddlHKPRC.SelectedValue;
            dt.Rows[(num - 1)]["JobDate"] = txtJobDate.Text != string.Empty ? txtJobDate.Text.Trim() + HK2009.Common.StringUtil.GetTime(txtJobDateH.Text.Trim()) : string.Empty;
           // dt.Rows[(num - 1)]["DeliveryDate"] = string.Empty;
            dt.Rows[(num - 1)]["ItemNO"] = txtItemNO.Text;
            dt.Rows[(num - 1)]["PCS"] = txtPCS.Text != string.Empty ? txtPCS.Text.Trim() : "0";
            dt.Rows[(num - 1)]["CTN"] = txtCTN.Text != string.Empty ? txtCTN.Text.Trim() : "0";
            dt.Rows[(num - 1)]["GrossWT"] = txtGrossWT.Text != string.Empty ? txtGrossWT.Text.Trim() : "0";
            dt.Rows[(num - 1)]["VOL"] = txtVOL.Text != string.Empty ? txtVOL.Text.Trim() : "0";
            dt.Rows[(num - 1)]["ContainerNO"] = txtContainerNO.Text;
            dt.Rows[(num - 1)]["SealNO"] = txtSealNO.Text;
            //dt.Rows[(num - 1)]["VV"] = txtVVD.Text;
            dt.Rows[(num - 1)]["PNNO"] = txtPNNO.Text;
            dt.Rows[(num - 1)]["BuyerPONO"] = string.Empty;
            dt.Rows[(num - 1)]["PCNO"] = txtPCNOD.Text;
            dt.Rows[(num - 1)]["CargoReadyDate"] = txtCargoReadyDate.Text;
            dt.Rows[(num - 1)]["TruckCO"] = string.Empty;
            dt.Rows[(num - 1)]["Remark"] = txtRemarkD.Text;
            dt.Rows[(num - 1)]["VendorName"] = vendorName;
            dt.Rows[(num - 1)]["WhouseName"] = whouseName;
            dt.Rows[(num - 1)]["PlaceName"] = placeName;
            dt.Rows[(num - 1)]["BespokeDate"] = string.Empty;
            dt.Rows[(num - 1)]["VendorLinkMan"] = ddlVendorLM.SelectedValue != string.Empty ? ddlVendorLM.SelectedValue : "0";
            dt.Rows[(num - 1)]["VendorLinkManName"] = vendorLinkManName;
            dt.Rows[(num - 1)]["SourceCode"] = txtSourceCode.Text.Trim();
            dt.Rows[(num - 1)]["AppointmentNO"] = txtAppointmentNO.Text.Trim();
        }
        else//添加第二条以上数据
        {
            dt = (DataTable)ViewState["BookingNoteDetail"];

            //for (int i = 0; i < dt.Rows.Count; i++)
            //{
            //    if (dt.Rows[i]["SONO"].ToString() == txtSONO.Text.Trim() && dt.Rows[i]["ItemNo"].ToString()==txtItemNO.Text.Trim())
            //    {
            //        Jscript.Alert("已存在SONO为" + txtSONO.Text.Trim() + "和ItemNO为" + txtItemNO.Text.Trim() + "的记录!");
            //        return;
            //    }
            //}

            dt.Rows.Add(new string[] {
                Convert.ToString(dt.Rows.Count+1),
                "0",
                txtConfirmNo.Text.Trim(),
                ddlVendor.SelectedValue,
                ddlWhouse.SelectedValue,
                "0",
                txtSONO.Text.Trim(),
                ddlFCLLCL.SelectedValue,
                ddlHKPRC.SelectedValue,
                txtJobDate.Text!=string.Empty?txtJobDate.Text.Trim() +HK2009.Common.StringUtil.GetTime(txtJobDateH.Text.Trim()):string.Empty,
                System.DBNull.Value.ToString(),
                txtItemNO.Text.Trim(),
                txtPCS.Text.Trim() !=string.Empty?txtPCS.Text.Trim():"0",
                txtCTN.Text.Trim()!=string.Empty?txtCTN.Text.Trim():"0",
                txtGrossWT.Text.Trim()!=string.Empty ?txtGrossWT.Text.Trim():"0",
                txtVOL.Text.Trim() !=string.Empty ? txtVOL.Text.Trim() :"0",
                txtContainerNO.Text.Trim(),
                txtSealNO.Text.Trim(),
                string.Empty,
                txtPNNO.Text.Trim(),
                string.Empty,
                txtPCNOD.Text.Trim(),
                txtCargoReadyDate.Text.Trim(),
                string.Empty,
                txtRemarkD.Text.Trim(),
                vendorName,
                whouseName,
                placeName,
                 System.DBNull.Value.ToString(),
                "0",
                ddlVendorLM.SelectedValue != string.Empty ?ddlVendorLM.SelectedValue:"0" ,
                vendorLinkManName,
                txtSourceCode.Text.Trim(),
                txtAppointmentNO.Text.Trim()
            });
        }

        ViewState["BookingNoteDetail"] = dt;
        dataBindDetail();
        ClearSelect();
    }
     

    private void ClearSelect()
    {
        txtConfirmNo.Text = string.Empty;
        ddlVendor.SelectedValue = "0";
        ddlWhouse.SelectedValue = "0";
       // ddlPlace.SelectedValue = "0";
        txtSONO.Text = string.Empty;
        ddlFCLLCL.SelectedValue = "FCL";
        ddlHKPRC.SelectedValue = "HK";
        txtJobDate.Text = string.Empty;
       // txtDeliveryDate.Text = string.Empty;
        txtItemNO.Text = string.Empty;
        txtPCS.Text = string.Empty;
        txtCTN.Text = string.Empty;
        txtGrossWT.Text = string.Empty;
        txtVOL.Text = string.Empty;
        txtContainerNO.Text = string.Empty;
        txtSealNO.Text = string.Empty;
        //txtVVD.Text = string.Empty;
        txtPNNO.Text = string.Empty;
        //txtBuyerPONO.Text = string.Empty;
        txtPCNOD.Text = string.Empty;
        txtCargoReadyDate.Text = string.Empty;
        //txtTruckCO.Text = string.Empty;
        txtRemarkD.Text = string.Empty;
       // bnDetailID  =string.Empty;
       // txtBespokeDate.Text = string.Empty;

        ddlVendorLM.Items.Clear();
        ddlVendorLM.DataBind();
        ddlVendorLM.Enabled = false;
        txtJobDateH.Text = string.Empty;
        num = -1;
        //txtSourceCode.Text = string.Empty;
        txtAppointmentNO.Text = string.Empty;
       
    }

    protected void btnClose_Click(object sender, EventArgs e)
    {
        ClearSelect();
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        if (Request["BookingNoteID"] != null)
        {

            BN_BookingNoteQuery bnQuery = bookingNoteManage.GetBookingNoteByPKID(int.Parse(Request["BookingNoteID"]));
            if (bnQuery != null)
            {
                //if (bnQuery.Status == int.Parse(Enums.BookingNoteStatus.CHECK.ToString("d")))
                //{
                //    Jscript.AlertInAjax(Resources.Messages.BookingnoteNotEdit, UpdatePanel1);
                //    return;
                //}

                //新添加的
                string templete = string.Empty;
                string emailTo = string.Empty;

                //修改原有的
                string templeteUp = string.Empty;
                string emailToUp = string.Empty;

                //删除原有的
                string templeteDel = string.Empty;
                string emailToDel = string.Empty;

                SqlParameter[] parms = null;
                List<SqlParameter> list = new List<SqlParameter>();
                 string sqlBooking = string.Empty;
                 string sqlBookingDtl = string.Empty;
                 string sqlJob = string.Empty;
                 string sqlJobDtl = string.Empty;

                 string sqlDelBooking = string.Empty;
                 string sqlDelJob = string.Empty;
                 string sqlDelBookingNote = string.Empty;

                 string sqlDelBooking2 = string.Empty;
                 string sqlDelJob2 = string.Empty;

                list.Add(new SqlParameter("@ShipperID", ddlShipper.SelectedValue));
                list.Add(new SqlParameter("@ShipperLMID", ddlShipperLM.SelectedValue));
                list.Add(new SqlParameter("@InvoiceNO", txtInvoiceNO.Text.Trim()));
                list.Add(new SqlParameter("@PcNO", txtPcNO.Text.Trim()));
                list.Add(new SqlParameter("@JobNumber",txtJobNumber.Text.Trim()));
                list.Add(new SqlParameter("@SourceCode",txtSourceCode.Text.Trim()));

                if (txtWinStart.Text == string.Empty)
                {
                    list.Add(new SqlParameter("@WinStart", System.DBNull.Value));
                }
                else
                {
                    list.Add(new SqlParameter("@WinStart", txtWinStart.Text));
                }

                if (txtWinClose.Text == string.Empty)
                {
                    list.Add(new SqlParameter("@WinClose", System.DBNull.Value));
                }
                else
                {
                    list.Add(new SqlParameter("@WinClose", txtWinClose.Text.Trim() + HK2009.Common.StringUtil.GetTime(txtWinCloseH.Text.Trim())));
                }

                if (txtWinLastClose.Text == string.Empty)
                {
                    list.Add(new SqlParameter("@WinLastClose", System.DBNull.Value));
                }
                else
                {

                    list.Add(new SqlParameter("@WinLastClose", txtWinLastClose.Text.Trim() + HK2009.Common.StringUtil.GetTime(txtWinLastCloseH.Text.Trim())));
                }
                list.Add(new SqlParameter("@CustomerID", ddlCustomer.SelectedValue));
                list.Add(new SqlParameter("@MarketID", ddlMarket.SelectedValue));
                list.Add(new SqlParameter("@DestinationID", ddlDestination.SelectedValue));
                list.Add(new SqlParameter("@CarrierForwar", ddlCarrierForwar.SelectedValue));
                list.Add(new SqlParameter("@LastModDate", DateTime.Now));
                list.Add(new SqlParameter("@LastModUser", Session["UserID"].ToString()));
                list.Add(new SqlParameter("@CreatedDate", DateTime.Now));
                list.Add(new SqlParameter("@CreatedUser", Session["UserID"].ToString()));

                list.Add(new SqlParameter("@VV", txtVVD.Text));

                if (txtSICutOFFDate.Text == string.Empty)
                {
                    list.Add(new SqlParameter("@SICutOFFDate", System.DBNull.Value));
                }
                else
                {
                    list.Add(new SqlParameter("@SICutOFFDate", txtSICutOFFDate.Text.Trim() + HK2009.Common.StringUtil.GetTime(txtSICutOFFDateH.Text.Trim())));
                }

                if (txtBillDate.Text == string.Empty)
                {
                    list.Add(new SqlParameter("@BillDate", System.DBNull.Value));
                }
                else
                {
                    list.Add(new SqlParameter("@BillDate", txtBillDate.Text));
                }
               
                list.Add(new SqlParameter("@CPO", txtCPO.Text.Trim()));
                list.Add(new SqlParameter("@Remark", txtRemark.Text.Trim()));
                list.Add(new SqlParameter("@BookingNoteID", Request["BookingNoteID"]));
                
                string sqlStr = @"update BN_BookingNote set ShipperID=@ShipperID,ShipperLMID=@ShipperLMID,InvoiceNO=@InvoiceNO,PcNO=@PcNO,WinStart=@WinStart,WinClose=@WinClose,
                            WinLastClose=@WinLastClose,CustomerID=@CustomerID,MarketID=@MarketID, DestinationID=@DestinationID,CarrierForwar=@CarrierForwar,LastModDate=@LastModDate,LastModUser=@LastModUser,
                            VV=@VV,SICutOFFDate=@SICutOFFDate,BillDate=@BillDate,CPO=@CPO,Remark=@Remark,JobNumber=@JobNumber,SourceCode=@SourceCode where PKID=@BookingNoteID;";



                DataTable dtSel = new DataTable();
                DataTable dtV = new DataTable();
                DataTable dtSel2 = new DataTable();

                DataTable dtBookingDtl = new DataTable();
                string sqlStrUp = string.Empty;

                 string vendorID = string.Empty;
                 int ii = 0;
                 int uii = 0;
                 string uvendorID=string.Empty;

                 if (ViewState["BookingNoteDetail"] != null && ((DataTable)ViewState["BookingNoteDetail"]).Rows.Count>0)
                 {
                     dtV = (DataTable)ViewState["BookingNoteDetail"];//缓存里的数据


                     if (dtV != null && dtV.Rows.Count > 0)
                     {
                         DataView view = dtV.DefaultView;
                         view.Sort = "VendorID asc";

                         for (int i = 0; i < view.Count; i++)
                         {
                             if (view[i]["BookingNoteDtlID"].ToString() == "0")//新添加的BookingNoteDtlID为0
                             {

                                 list.Add(new SqlParameter("@ConfirmNO" + i.ToString(), view[i]["ConfirmNO"].ToString()));
                                 list.Add(new SqlParameter("@VendorID" + i.ToString(), view[i]["VendorID"].ToString()));
                                 list.Add(new SqlParameter("@WhouseID" + i.ToString(), view[i]["WhouseID"].ToString()));
                                 list.Add(new SqlParameter("@PlaceID" + i.ToString(), view[i]["PlaceID"].ToString()));

                                 list.Add(new SqlParameter("@SONO" + i.ToString(), view[i]["SONO"].ToString()));
                                 list.Add(new SqlParameter("@FCLLCL" + i.ToString(), view[i]["FCLLCL"].ToString()));
                                 list.Add(new SqlParameter("@HKPRC" + i.ToString(), view[i]["HKPRC"].ToString()));
                                 list.Add(new SqlParameter("@SourceCode" + i.ToString(),view[i]["SourceCode"].ToString()));


                                 list.Add(new SqlParameter("@StatusDtl" + i.ToString(), Enums.BookingNoteDtlStatus.BOOKING.ToString("d")));
                                 list.Add(new SqlParameter("@BookingDate" + i.ToString(), DateTime.Now));

                                 int userIDs = 0;
                                 string sqlUsers = "select UserID from Users where LoginID='" + view[i]["VendorLinkManName"].ToString() + "'";
                                 DataTable dtUsers = db.RunSql(sqlUsers);
                                 if (dtUsers != null && dtUsers.Rows.Count > 0)
                                 {
                                     int.TryParse(dtUsers.Rows[0]["UserID"].ToString(), out userIDs);
                                 }


                                 list.Add(new SqlParameter("@BookingUser" + i.ToString(),Session["UserID"].ToString() ));//userIDs

                                 if (view[i]["JobDate"].ToString() == string.Empty)
                                 {
                                     list.Add(new SqlParameter("@JobDate" + i.ToString(), System.DBNull.Value));
                                     //list.Add(new SqlParameter("@StatusDtl" + i.ToString(), Enums.BookingNoteDtlStatus.NEW.ToString("d")));
                                     //list.Add(new SqlParameter("@BookingDate" + i.ToString(), System.DBNull.Value));
                                     //list.Add(new SqlParameter("@BookingUser" + i.ToString(), System.DBNull.Value));
                                 }
                                 //添加到booking相关表
                                 else
                                 {
                                     list.Add(new SqlParameter("@JobDate" + i.ToString(), view[i]["JobDate"].ToString()));                                   

//                                     if (vendorID.Contains(view[i]["VendorID"].ToString()))
//                                     {
//                                         sqlBookingDtl += @"INSERT INTO BN_BookingDtl(BookingID,BookingNoteDtlID,ShipperID,SONO,PNNO,WinStart,
//                                            WinClose, JobDate,DeliveryDate,WhouseID,FCLLCL,ItemNO,PCS,CTN,GrossWT,VOL,Remark,PlaceID)
//                                            VALUES(@BookingIDReturn" + ii.ToString() + ",@BookingDtlReturn" + i.ToString() + ",@ShipperID,@SONO" + i.ToString()
//                                                         + ",@PNNO" + i.ToString() + ",@WinStart,@WinClose,@JobDate" + i.ToString() + ",@DeliveryDate" + i.ToString()
//                                                         + ",@WhouseID" + i.ToString() + ",@FCLLCL" + i.ToString() + ",@ItemNO" + i.ToString()
//                                                         + ",@PCS" + i.ToString() + ",@CTN" + i.ToString() + ",@GrossWT" + i.ToString() + ",@VOL" + i.ToString()
//                                                         + ",@Remark2" + i.ToString() + ",@PlaceID" + i.ToString() + ");";
//                                     }
                                     //else
                                     //{
                                        


                                     //}

                                    // vendorID += view[i]["VendorID"].ToString() + ",";


                                     List<string> emailList = new List<string>();
                                     string sqlStrSelect = string.Empty;

                                     // 读取托运人的联络人email
//                                     sqlStrSelect = @"SELECT * 
//                            FROM Sy_ClientLinkMan where PKID=@PKID";
                                     DataTable dtEmail;

                                     SqlParameter[] parmsSelect = null;

                                     //parmsSelect = new SqlParameter[1];
                                     //parmsSelect[0] = new SqlParameter("@PKID", ddlShipperLM.SelectedValue);
                                     //dtEmail = db.RunSqlTab(sqlStrSelect, parmsSelect);
                                     //if (dtEmail != null && dtEmail.Rows.Count > 0)
                                     //{
                                     //    foreach (DataRow row in dtEmail.Rows)
                                     //    {
                                     //        emailList.Add(row["Email"].ToString());
                                     //    }
                                     //}

                                     // 读取工厂的联络人email
                                     sqlStrSelect = @"SELECT * 
                            FROM Sy_ClientLinkMan where PKID=@PKID";

                                     parmsSelect = new SqlParameter[1];
                                     parmsSelect[0] = new SqlParameter("@PKID", view[i]["VendorLinkMan"].ToString());
                                     dtEmail = db.RunSqlTab(sqlStrSelect, parmsSelect);
                                     if (dtEmail != null && dtEmail.Rows.Count > 0)
                                     {
                                         foreach (DataRow row in dtEmail.Rows)
                                         {
                                             emailList.Add(row["Email"].ToString());
                                         }
                                     }

//                                     // 读取公司联系人email
//                                     string sqlStrComp = @"SELECT users.*
//                               FROM Users users INNER JOIN
//                                    Sy_Client ON users.UserID = Sy_Client.CompanyBP
//                               WHERE Sy_Client.PKID = @VendorID";
//                                     SqlParameter[] parmsComp = new SqlParameter[1];
//                                     parmsComp[0] = new SqlParameter("@VendorID", view[i]["VendorID"].ToString());
//                                     dtEmail = db.RunSqlTab(sqlStrComp, parmsComp);
//                                     if (dtEmail != null && dtEmail.Rows.Count > 0)
//                                     {
//                                         foreach (DataRow row in dtEmail.Rows)
//                                         {
//                                             emailList.Add(row["Email"].ToString());
//                                         }
//                                     }

                                     // 读取自己的email
                                     string sqlStrComp = "SELECT * FROM Users WHERE UserID = @UserID";
                                     SqlParameter[] parmsMy = new SqlParameter[1];
                                     parmsMy[0] = new SqlParameter("@UserID", Session["UserID"].ToString());
                                     dtEmail = db.RunSqlTab(sqlStrComp, parmsMy);
                                     if (dtEmail != null && dtEmail.Rows.Count > 0)
                                     {
                                         foreach (DataRow row in dtEmail.Rows)
                                         {
                                             emailList.Add(row["Email"].ToString());
                                         }
                                     }


                                     //发email模板
                                     templete += @"


[list]




                               ";
                                     string dateFormat = "yyyy-MM-dd HH:mm:ss";
                                     string change = string.Empty;

                                     change = change + "ItemNO:" + view[i]["ItemNO"].ToString() + @"

";
                                     change = change + "SONO:" + view[i]["SONO"].ToString() + @"

";
                                     change = change + "PNNO:" + view[i]["PNNO"].ToString() + @"

";
                                     change = change + "Added by:" + Session["LoginID"].ToString() + @"

";

                                     change += "Added JobDate to:" + DateTime.Parse(view[i]["JobDate"].ToString()).ToString(dateFormat) + @"
";



                                     templete = templete.Replace("[list]", change);


                                     foreach (string email in emailList)
                                     {
                                         if (StringUtil.IsEmailAddress(email))
                                         {
                                             //templete = templete.Replace("[title]", email);
                                             emailTo += email + ",";
                                         }
                                     }
                                     if (emailTo != string.Empty)
                                     {
                                         emailTo = emailTo.Substring(0, emailTo.Length - 1) + ";";
                                     }
                                     templete += "}";

                                 }

                                 ii += 1;

                                 SqlParameter parmBID = new SqlParameter("@BookingIDReturn" + ii.ToString(), 0);
                                 parmBID.Direction = ParameterDirection.Output;
                                 parmBID.SqlDbType = SqlDbType.Int;
                                 list.Add(parmBID);

                                 sqlBooking += @"INSERT INTO BN_Booking(BookingNO,Status,VendorID,BookingUser,BookingDate)
                                         VALUES(dbo.Fn_NextBookingNO(), @StatusBooking, @VendorID" + i.ToString() + ", @BookingUser" + i.ToString() + ", GETDATE()) SET @BookingIDReturn" + ii.ToString() + "=@@Identity; ";

                                 sqlBookingDtl += @"INSERT INTO BN_BookingDtl(BookingID,BookingNoteDtlID,ShipperID,SONO,PNNO,WinStart,
                                            WinClose, JobDate,DeliveryDate,WhouseID,FCLLCL,ItemNO,PCS,CTN,GrossWT,VOL,Remark,PlaceID)
                                            VALUES(@BookingIDReturn" + ii.ToString() + ",@BookingDtlReturn" + i.ToString() + ",@ShipperID,@SONO" + i.ToString()
                                                      + ",@PNNO" + i.ToString() + ",@WinStart,@WinClose,@JobDate" + i.ToString() + ",@DeliveryDate" + i.ToString()
                                                      + ",@WhouseID" + i.ToString() + ",@FCLLCL" + i.ToString() + ",@ItemNO" + i.ToString()
                                                      + ",@PCS" + i.ToString() + ",@CTN" + i.ToString() + ",@GrossWT" + i.ToString() + ",@VOL" + i.ToString()
                                                      + ",@Remark2" + i.ToString() + ",@PlaceID" + i.ToString() + ");";


                                 if (view[i]["DeliveryDate"].ToString() == string.Empty)
                                 {
                                     list.Add(new SqlParameter("@DeliveryDate" + i.ToString(), System.DBNull.Value));
                                 }
                                 else
                                 {
                                     list.Add(new SqlParameter("@DeliveryDate" + i.ToString(), view[i]["DeliveryDate"].ToString()));
                                 }

                                 list.Add(new SqlParameter("@ItemNO" + i.ToString(), view[i]["ItemNO"].ToString()));
                                 list.Add(new SqlParameter("@PCS" + i.ToString(), view[i]["PCS"].ToString()));
                                 list.Add(new SqlParameter("@CTN" + i.ToString(), view[i]["CTN"].ToString()));

                                 list.Add(new SqlParameter("@GrossWT" + i.ToString(), view[i]["GrossWT"].ToString()));
                                 list.Add(new SqlParameter("@VOL" + i.ToString(), view[i]["VOL"].ToString()));
                                 list.Add(new SqlParameter("@ContainerNO" + i.ToString(), view[i]["ContainerNO"].ToString()));
                                 list.Add(new SqlParameter("@SealNO" + i.ToString(), view[i]["SealNO"].ToString()));
                                 list.Add(new SqlParameter("@VV2" + i.ToString(), view[i]["VV"].ToString()));

                                 list.Add(new SqlParameter("@PNNO" + i.ToString(), view[i]["PNNO"].ToString()));
                                 list.Add(new SqlParameter("@BuyerPONO" + i.ToString(), view[i]["BuyerPONO"].ToString()));
                                 list.Add(new SqlParameter("@PCNO" + i.ToString(), view[i]["PCNO"].ToString()));
                                 list.Add(new SqlParameter("@VendorLinkMan" + i.ToString(), view[i]["VendorLinkMan"].ToString()));

                                 SqlParameter parmBDtl = new SqlParameter("@BookingDtlReturn" + i.ToString(), 0);
                                 parmBDtl.SqlDbType = SqlDbType.Int;
                                 parmBDtl.Direction = ParameterDirection.Output;
                                 list.Add(parmBDtl);


                                 if (view[i]["CargoReadyDate"].ToString() == string.Empty)
                                 {
                                     list.Add(new SqlParameter("@CargoReadyDate" + i.ToString(), System.DBNull.Value));
                                 }
                                 else
                                 {
                                     list.Add(new SqlParameter("@CargoReadyDate" + i.ToString(), view[i]["CargoReadyDate"].ToString()));
                                 }

                                 list.Add(new SqlParameter("@TruckCO" + i.ToString(), view[i]["TruckCO"].ToString()));
                                 list.Add(new SqlParameter("@Remark2" + i.ToString(), view[i]["Remark"].ToString()));

                                 if (view[i]["BespokeDate"].ToString() == string.Empty)
                                 {
                                     list.Add(new SqlParameter("@BespokeDate" + i.ToString(), System.DBNull.Value));
                                 }
                                 else
                                 {
                                     list.Add(new SqlParameter("@BespokeDate" + i.ToString(), view[i]["BespokeDate"].ToString()));
                                 }



                                 sqlStr += @"INSERT INTO BN_BookingNoteDtl(BookingNoteID,ConfirmNO,VendorID,WhouseID,PlaceID,SONO,FCLLCL,HKPRC,JobDate,DeliveryDate,
                               ItemNO,PCS,CTN,GrossWT,VOL,ContainerNO,SealNO,VV,CreatedDate,CreatedUser,Status,PNNO,BuyerPONO,PCNO,CargoReadyDate,TruckCO,Remark,BespokeDate,VendorLinkMan,BookingDate,BookingUser,SourceCode)
                               VALUES(@BookingNoteID,@ConfirmNO" + i.ToString() + ",@VendorID" + i.ToString() + ",@WhouseID" + i.ToString() + ",@PlaceID" + i.ToString() + ",";

                                 sqlStr += "@SONO" + i.ToString() + ",@FCLLCL" + i.ToString() + ",@HKPRC" + i.ToString() + ",@JobDate" + i.ToString() + ",@DeliveryDate" + i.ToString() + ",";
                                 sqlStr += "@ItemNO" + i.ToString() + ",@PCS" + i.ToString() + ",@CTN" + i.ToString() + ",@GrossWT" + i.ToString() + ",@VOL" + i.ToString() + ",";
                                 sqlStr += "@ContainerNO" + i.ToString() + ",@SealNO" + i.ToString() + ",@VV2" + i.ToString() + ",@CreatedDate,@CreatedUser,@StatusDtl" + i.ToString() + ",@PNNO" + i.ToString() + ",";
                                 sqlStr += "@BuyerPONO" + i.ToString() + ",@PCNO" + i.ToString() + ",@CargoReadyDate" + i.ToString() + ",@TruckCO" + i.ToString() + ",@Remark2" + i.ToString() + ",@BespokeDate" + i.ToString() + ",@VendorLinkMan" + i.ToString() + ",@BookingDate" + i.ToString() + ",@BookingUser" + i.ToString() + ",@SourceCode" + i.ToString() + ") SET @BookingDtlReturn" + i.ToString() + "=@@Identity;";
                             }
                         }

                         list.Add(new SqlParameter("@StatusBooking", Enums.BookingStatus.NEW.ToString("d")));

                       
                         for (int j = 0; j < view.Count; j++)
                         {
                             if (view[j]["BookingNoteDtlID"].ToString() != "0")//更新缓存中原数据库上存在的数据到数据库
                             {
                                 BN_BookingNoteDtlQuery bookingNoteDtlQuery = bookingNoteManage.GetBookingNoteDetailByID(int.Parse(view[j]["BookingNoteDtlID"].ToString()));
                                 if (bookingNoteDtlQuery != null)
                                 {
                                     list.Add(new SqlParameter("@UpBookingDtlReturnu" + j.ToString(), bookingNoteDtlQuery.PKID.ToString()));
                                     list.Add(new SqlParameter("@ConfirmNOu" + j.ToString(), view[j]["ConfirmNO"].ToString()));
                                     list.Add(new SqlParameter("@VendorIDu" + j.ToString(), view[j]["VendorID"].ToString()));
                                     list.Add(new SqlParameter("@WhouseIDu" + j.ToString(), view[j]["WhouseID"].ToString()));
                                     list.Add(new SqlParameter("@PlaceIDu" + j.ToString(), view[j]["PlaceID"].ToString()));

                                     list.Add(new SqlParameter("@SONOu" + j.ToString(), view[j]["SONO"].ToString()));
                                     list.Add(new SqlParameter("@FCLLCLu" + j.ToString(), view[j]["FCLLCL"].ToString()));
                                     list.Add(new SqlParameter("@HKPRCu" + j.ToString(), view[j]["HKPRC"].ToString()));


                                     list.Add(new SqlParameter("@StatusDtlu" + j.ToString(), Enums.BookingNoteDtlStatus.BOOKING.ToString("d")));
                                     list.Add(new SqlParameter("@BookingDateu" + j.ToString(), DateTime.Now));

                                     list.Add(new SqlParameter("@Appointmentu" + j.ToString(),view[j]["AppointmentNO"].ToString()));


                                     int userIDs = 0;
                                     string sqlUsers = "select UserID from Users where LoginID='" + view[j]["VendorLinkManName"].ToString() + "'";
                                     DataTable dtUsers = db.RunSql(sqlUsers);
                                     if (dtUsers != null && dtUsers.Rows.Count > 0)
                                     {
                                         int.TryParse(dtUsers.Rows[0]["UserID"].ToString(), out userIDs);
                                     }


                                     list.Add(new SqlParameter("@BookingUseru" + j.ToString(), userIDs));

                                     if (view[j]["JobDate"].ToString() != string.Empty)//缓存存在收货日期
                                     {
                                         list.Add(new SqlParameter("@JobDateu" + j.ToString(), view[j]["JobDate"].ToString()));
                                     }
                                     else
                                     {
                                         list.Add(new SqlParameter("@JobDateu" + j.ToString(), System.DBNull.Value));
                                     }

                                         sqlBooking += @"UPDATE BN_Booking SET Status=@StatusBooking,VendorID=@VendorIDu" + j.ToString() +
                                         ",BookingUser=@BookingUseru" + j.ToString() + ",BookingDate=GETDATE()" + " WHERE PKID =(select BookingID from BN_BookingDtl where BookingNoteDtlID=@UpBookingDtlReturnu" + j.ToString() + ");";

                                         sqlBookingDtl += @"UPDATE  BN_BookingDtl SET ShipperID=@ShipperID,SONO=@SONOu" + j.ToString()
                                         + ",PNNO=@PNNOu" + j.ToString() + ",WinStart=@WinStart,WinClose=@WinClose,JobDate=@JobDateu" + j.ToString()
                                         + ",DeliveryDate=@DeliveryDateu" + j.ToString()
                                         + ",WhouseID=@WhouseIDu" + j.ToString() + ",FCLLCL=@FCLLCLu" + j.ToString() + ",ItemNO=@ItemNOu" + j.ToString()
                                         + ",PCS=@PCSu" + j.ToString() + ",CTN=@CTNu" + j.ToString() + ",GrossWT=@GrossWTu" + j.ToString() + ",VOL=@VOLu" + j.ToString()
                                         + ",Remark=@Remark2u" + j.ToString() + ",PlaceID=@PlaceIDu" + j.ToString() + ",Appointament=@Appointmentu" + j.ToString() + " WHERE BookingNoteDtlID=@UpBookingDtlReturnu" + j.ToString() + ";";


                                         string sqlJobS = "select * from BN_ShippingOrderDtl where BookingDtlID=(select PKID from BN_BookingDtl where BookingNoteDtlID=" + bookingNoteDtlQuery.PKID.ToString() + ")";
                                         DataTable dtJobS = db.RunSql(sqlJobS);

                                         if (dtJobS != null && dtJobS.Rows.Count > 0)//更新booking相关表时判断下Job该booking是否已分配job，如果已经分配了就更新job相关表
                                         {
                                             sqlJob += @" update BN_ShippingOrder set VendorID =@VendorIDu" + j.ToString() + ",Appointament=@Appointmentu" + j.ToString()
                                                    + " where BookingID =(select BookingID from BN_BookingDtl where BookingNoteDtlID=@UpBookingDtlReturnu" + j.ToString() + ");";

                                             sqlJobDtl += @"UPDATE  BN_ShippingOrderDtl SET ShipperID=@ShipperID,SONO=@SONOu" + j.ToString()
                                         + ",PNNO=@PNNOu" + j.ToString() + ",WinStart=@WinStart,WinClose=@WinClose,JobDate=@JobDateu" + j.ToString()
                                         + ",DeliveryDate=@DeliveryDateu" + j.ToString()
                                         + ",WhouseID=@WhouseIDu" + j.ToString() + ",FCLLCL=@FCLLCLu" + j.ToString() + ",ItemNO=@ItemNOu" + j.ToString()
                                         + ",PCS=@PCSu" + j.ToString() + ",CTN=@CTNu" + j.ToString() + ",GrossWT=@GrossWTu" + j.ToString() + ",VOL=@VOLu" + j.ToString()
                                         + ",Remark=@Remark2u" + j.ToString() + ",PlaceID=@PlaceIDu" + j.ToString() + " WHERE BookingDtlID=(select PKID from BN_BookingDtl where BookingNoteDtlID=@UpBookingDtlReturnu" + j.ToString() + ");";

                                         }


                                   

                                     //else //缓存不存在收货日期，
                                     //{
                                     //    list.Add(new SqlParameter("@JobDateu" + j.ToString(), System.DBNull.Value));
                                     //    if (bookingNoteDtlQuery.JobDate != DateTime.MinValue)//数据库存在收货日期
                                     //    {
                                     //        sqlBooking += @"UPDATE BN_Booking SET Status=@StatusBooking,VendorID=@VendorIDu" + j.ToString()
                                     //      + " WHERE PKID =(select BookingID from BN_BookingDtl where BookingNoteDtlID=@UpBookingDtlReturnu" + j.ToString() + ");";

                                     //        sqlBookingDtl += @"UPDATE  BN_BookingDtl SET ShipperID=@ShipperID,SONO=@SONOu" + j.ToString()
                                     //        + ",PNNO=@PNNOu" + j.ToString() + ",WinStart=@WinStart,WinClose=@WinClose,JobDate=@JobDateu" + j.ToString()
                                     //        + ",DeliveryDate=@DeliveryDateu" + j.ToString()
                                     //        + ",WhouseID=@WhouseIDu" + j.ToString() + ",FCLLCL=@FCLLCLu" + j.ToString() + ",ItemNO=@ItemNOu" + j.ToString()
                                     //        + ",PCS=@PCSu" + j.ToString() + ",CTN=@CTNu" + j.ToString() + ",GrossWT=@GrossWTu" + j.ToString() + ",VOL=@VOLu" + j.ToString()
                                     //        + ",Remark=@Remark2u" + j.ToString() + ",PlaceID=@PlaceIDu" + j.ToString() + ",Appointament=@Appointmentu" + j.ToString() + " WHERE BookingNoteDtlID=@UpBookingDtlReturnu" + j.ToString() + ";";

                                     //        string sqlJobS = "select * from BN_ShippingOrderDtl where BookingDtlID=(select PKID from BN_BookingDtl where BookingNoteDtlID=" + bookingNoteDtlQuery.PKID.ToString() + ")";
                                     //        DataTable dtJobS = db.RunSql(sqlJobS);

                                     //        if (dtJobS != null && dtJobS.Rows.Count > 0)//更新booking相关表时判断下Job该booking是否已分配job，如果已经分配了就更新job相关表
                                     //        {
                                     //            sqlJob += @" update BN_ShippingOrder set VendorID =@VendorIDu" + j.ToString() + ",Appointament=@Appointmentu" + j.ToString()
                                     //                   + " where  BookingID =(select BookingID from BN_BookingDtl where BookingNoteDtlID=@UpBookingDtlReturnu" + j.ToString() + ");";

                                     //            sqlJobDtl += @"UPDATE  BN_ShippingOrderDtl SET ShipperID=@ShipperID,SONO=@SONOu" + j.ToString()
                                     //        + ",PNNO=@PNNOu" + j.ToString() + ",WinStart=@WinStart,WinClose=@WinClose,JobDate=@JobDateu" + j.ToString()
                                     //        + ",DeliveryDate=@DeliveryDateu" + j.ToString()
                                     //        + ",WhouseID=@WhouseIDu" + j.ToString() + ",FCLLCL=@FCLLCLu" + j.ToString() + ",ItemNO=@ItemNOu" + j.ToString()
                                     //        + ",PCS=@PCSu" + j.ToString() + ",CTN=@CTNu" + j.ToString() + ",GrossWT=@GrossWTu" + j.ToString() + ",VOL=@VOLu" + j.ToString()
                                     //        + ",Remark=@Remark2u" + j.ToString() + ",PlaceID=@PlaceIDu" + j.ToString() + " WHERE BookingDtlID=(select PKID from BN_BookingDtl where BookingNoteDtlID=@UpBookingDtlReturnu" + j.ToString() + ");";

                                     //        }

                                     //    }
                                     //}

                                     if (view[j]["DeliveryDate"].ToString() == string.Empty)
                                     {
                                         list.Add(new SqlParameter("@DeliveryDateu" + j.ToString(), System.DBNull.Value));
                                     }
                                     else
                                     {
                                         list.Add(new SqlParameter("@DeliveryDateu" + j.ToString(), view[j]["DeliveryDate"].ToString()));
                                     }

                                     list.Add(new SqlParameter("@ItemNOu" + j.ToString(), view[j]["ItemNO"].ToString()));
                                     list.Add(new SqlParameter("@PCSu" + j.ToString(), view[j]["PCS"].ToString()));
                                     list.Add(new SqlParameter("@CTNu" + j.ToString(), view[j]["CTN"].ToString()));

                                     list.Add(new SqlParameter("@GrossWTu" + j.ToString(), view[j]["GrossWT"].ToString()));
                                     list.Add(new SqlParameter("@VOLu" + j.ToString(), view[j]["VOL"].ToString()));
                                     list.Add(new SqlParameter("@ContainerNOu" + j.ToString(), view[j]["ContainerNO"].ToString()));
                                     list.Add(new SqlParameter("@SealNOu" + j.ToString(), view[j]["SealNO"].ToString()));
                                     list.Add(new SqlParameter("@VV2u" + j.ToString(), view[j]["VV"].ToString()));

                                     list.Add(new SqlParameter("@PNNOu" + j.ToString(), view[j]["PNNO"].ToString()));
                                     list.Add(new SqlParameter("@BuyerPONOu" + j.ToString(), view[j]["BuyerPONO"].ToString()));
                                     list.Add(new SqlParameter("@PCNOu" + j.ToString(), view[j]["PCNO"].ToString()));
                                     list.Add(new SqlParameter("@VendorLinkManu" + j.ToString(), view[j]["VendorLinkMan"].ToString()));

                                     list.Add(new SqlParameter("@SourceCodeu" + j.ToString(),view[j]["SourceCode"].ToString()));

                                     if (view[j]["CargoReadyDate"].ToString() == string.Empty)
                                     {
                                         list.Add(new SqlParameter("@CargoReadyDateu" + j.ToString(), System.DBNull.Value));
                                     }
                                     else
                                     {
                                         list.Add(new SqlParameter("@CargoReadyDateu" + j.ToString(), view[j]["CargoReadyDate"].ToString()));
                                     }

                                     list.Add(new SqlParameter("@TruckCOu" + j.ToString(), view[j]["TruckCO"].ToString()));
                                     list.Add(new SqlParameter("@Remark2u" + j.ToString(), view[j]["Remark"].ToString()));

                                     if (view[j]["BespokeDate"].ToString() == string.Empty)
                                     {
                                         list.Add(new SqlParameter("@BespokeDateu" + j.ToString(), System.DBNull.Value));
                                     }
                                     else
                                     {
                                         list.Add(new SqlParameter("@BespokeDateu" + j.ToString(), view[j]["BespokeDate"].ToString()));
                                     }

                                     sqlStr += @" UPDATE BN_BookingNoteDtl SET ConfirmNO=@ConfirmNOu" + j.ToString() + ",VendorID=@VendorIDu" + j.ToString()
                                         + ",WhouseID=@WhouseIDu" + j.ToString() + ",PlaceID=@PlaceIDu" + j.ToString() + ",SONO=@SONOu" + j.ToString() + ",FCLLCL=@FCLLCLu" + j.ToString()
                                         + ",HKPRC=@HKPRCu" + j.ToString() + ",JobDate=@JobDateu" + j.ToString() + ",DeliveryDate=@DeliveryDateu" + j.ToString()
                                         + ",ItemNO=@ItemNOu" + j.ToString() + ",PCS=@PCSu" + j.ToString() + ",CTN=@CTNu" + j.ToString() + ",GrossWT=@GrossWTu" + j.ToString()
                                         + ",VOL=@VOLu" + j.ToString() + ",ContainerNO=@ContainerNOu" + j.ToString() + ",SealNO=@SealNOu" + j.ToString() + ",VV=@VV2u" + j.ToString()
                                         + ",PNNO=@PNNOu" + j.ToString() + ",BuyerPONO=@BuyerPONOu" + j.ToString() + ",PCNO=@PCNOu" + j.ToString() + ",CargoReadyDate=@CargoReadyDateu" + j.ToString()
                                         + ",TruckCO=@TruckCOu" + j.ToString() + ",Remark=@Remark2u" + j.ToString() + ",BespokeDate=@BespokeDateu" + j.ToString() + ",VendorLinkMan=@VendorLinkManu" + j.ToString() + ",SourceCode=@SourceCodeu" + j.ToString() + ",Appointament=@Appointmentu" + j.ToString() + " where PKID=@UpBookingDtlReturnu" + j.ToString() + ";";


                                 }


                                 //修改原数据库时发email

                                 List<string> emailList = new List<string>();
                                 string sqlStrSelect = string.Empty;

                                 // 读取托运人的联络人email
//                                 sqlStrSelect = @"SELECT * 
//                            FROM Sy_ClientLinkMan where PKID=@PKID";
                                 DataTable dtEmail;

                                 SqlParameter[] parmsSelect = null;

                                 //parmsSelect = new SqlParameter[1];
                                 //parmsSelect[0] = new SqlParameter("@PKID", ddlShipperLM.SelectedValue);
                                 //dtEmail = db.RunSqlTab(sqlStrSelect, parmsSelect);
                                 //if (dtEmail != null && dtEmail.Rows.Count > 0)
                                 //{
                                 //    foreach (DataRow row in dtEmail.Rows)
                                 //    {
                                 //        emailList.Add(row["Email"].ToString());
                                 //    }
                                 //}

                                 // 读取工厂的联络人email
                                 sqlStrSelect = @"SELECT * 
                            FROM Sy_ClientLinkMan where PKID=@PKID";

                                 parmsSelect = new SqlParameter[1];
                                 parmsSelect[0] = new SqlParameter("@PKID", view[j]["VendorLinkMan"].ToString());
                                 dtEmail = db.RunSqlTab(sqlStrSelect, parmsSelect);
                                 if (dtEmail != null && dtEmail.Rows.Count > 0)
                                 {
                                     foreach (DataRow row in dtEmail.Rows)
                                     {
                                         emailList.Add(row["Email"].ToString());
                                     }
                                 }

                                 //                        // 读取公司联系人email
                                 //                      string sqlStrComp = @"SELECT users.*
                                 //                               FROM Users users INNER JOIN
                                 //                                    Sy_Client ON users.UserID = Sy_Client.CompanyBP
                                 //                               WHERE Sy_Client.PKID = @VendorID";
                                 //                      SqlParameter[] parmsComp = new SqlParameter[1];
                                 //                      parmsComp[0] = new SqlParameter("@VendorID", view[i]["VendorID"].ToString());
                                 //                      dtEmail = db.RunSqlTab(sqlStrComp, parmsComp);
                                 //                        if (dtEmail != null && dtEmail.Rows.Count > 0)
                                 //                        {
                                 //                            foreach (DataRow row in dtEmail.Rows)
                                 //                            {
                                 //                                emailList.Add(row["Email"].ToString());
                                 //                            }
                                 //                        }

                                 // 读取自己的email
                                 string sqlStrComp = "SELECT * FROM Users WHERE UserID = @UserID";
                                 SqlParameter[] parmsMy = new SqlParameter[1];
                                 parmsMy[0] = new SqlParameter("@UserID", Session["UserID"].ToString());
                                 dtEmail = db.RunSqlTab(sqlStrComp, parmsMy);
                                 if (dtEmail != null && dtEmail.Rows.Count > 0)
                                 {
                                     foreach (DataRow row in dtEmail.Rows)
                                     {
                                         emailList.Add(row["Email"].ToString());
                                     }
                                 }


                                 //判断该托运单是否已分配，如果已分配就发给运输队
                                 string sqlJobSs = "select * from BN_ShippingOrderDtl where BookingDtlID=(select PKID from BN_BookingDtl where BookingNoteDtlID=" + bookingNoteDtlQuery.PKID.ToString() + ")";
                                 DataTable dtJobSs = db.RunSql(sqlJobSs);

                                 if (dtJobSs != null && dtJobSs.Rows.Count > 0)//更新booking相关表时判断下Job该booking是否已分配job，如果已经分配了就发email到运输队
                                 {
                                     for (int i = 0; i < dtJobSs.Rows.Count; i++)
                                     { 
                                        //读取运输队的联络人email
                                         sqlStrSelect = @"select  * 
                                         FROM Sy_ClientLinkMan where ClientID=(select Contractor from BN_BookingDtl where PKID=
                                        (select BookingDtlID from BN_ShippingOrderDtl where PKID=@PKID))";

                                         parmsSelect = new SqlParameter[1];
                                         parmsSelect[0] = new SqlParameter("@PKID", dtJobSs.Rows[i]["PKID"].ToString());
                                         dtEmail = db.RunSqlTab(sqlStrSelect, parmsSelect);
                                         if (dtEmail != null && dtEmail.Rows.Count > 0)
                                         {
                                             foreach (DataRow row in dtEmail.Rows)
                                             {
                                                 emailList.Add(row["Email"].ToString());
                                             }
                                         }
                                     }
                                 }


                                 //发email模板
                                 templeteUp += @"


[list]


                               ";
                                 string dateFormat = "yyyy-MM-dd HH:mm:ss";
                                 string change = string.Empty;

                                 change = change + "ItemNO:" + view[j]["ItemNO"].ToString() + @"

";
                                 change = change + "SONO:" + view[j]["SONO"].ToString() + @"

";
                                 change = change + "PNNO:" + view[j]["PNNO"].ToString() + @"

";
                                 change = change + "Edited by:" + Session["LoginID"].ToString() + @"

";

                                 if (view[j]["JobDate"].ToString() != string.Empty)
                                 {
                                     change += "changed JobDate to:" + DateTime.Parse(view[j]["JobDate"].ToString()).ToString(dateFormat) + @"
";
                                 }
                                 else
                                 {
                                     change += "changed JobDate to: null";
                                 }


                                 templeteUp = templeteUp.Replace("[list]", change);


                                 foreach (string email in emailList)
                                 {
                                     if (StringUtil.IsEmailAddress(email))
                                     {
                                         //templete = templete.Replace("[title]", email);
                                         emailToUp += email + ",";
                                     }
                                 }
                                 if (emailToUp != string.Empty)
                                 {
                                     emailToUp = emailToUp.Substring(0, emailToUp.Length - 1) + ";";
                                 }
                                 templeteUp += "}";

                             }
                         }


                         //删除了原来数据库中的数据的处理

                         DataTable dtoBookingDtls = bookingNoteManage.GetBookingNoteDtlByBookingNoteID(int.Parse(Request["BookingNoteID"]));
                         DataTable dtDel = new DataTable();
                         // DataRowCollection rowColl =dtDel.Rows;                       
                         ArrayList lst = new ArrayList();

                         dtDel.Columns.Add("PKID");
                         dtDel.Columns.Add("ItemNO");
                         dtDel.Columns.Add("SONO");
                         dtDel.Columns.Add("PNNO");

                         if (dtoBookingDtls != null && dtoBookingDtls.Rows.Count > 0)
                         {
                             for (int d = 0; d < dtoBookingDtls.Rows.Count; d++)
                             {
                                 bool isexit = false;

                                 for (int dd = 0; dd < dtV.Rows.Count; dd++)
                                 {
                                     if (dtoBookingDtls.Rows[d]["PKID"].ToString() == dtV.Rows[dd]["BookingNoteDtlID"].ToString())
                                     {                                         
                                         isexit = true;
                                         break;
                                     }
                                 }
                                 if (!isexit)
                                 {
                                     dtDel.Rows.Add(new string[] {                            
                                        dtoBookingDtls.Rows[d]["PKID"].ToString(),
                                        dtoBookingDtls.Rows[d]["ItemNO"].ToString(),
                                        dtoBookingDtls.Rows[d]["SONO"].ToString(),
                                        dtoBookingDtls.Rows[d]["PNNO"].ToString()
             
                                             });
                                 }
                             }
                         }


                         if (dtDel != null && dtDel.Rows.Count > 0)//删除了的原数据库数据
                         {
                             List<string> emailList = new List<string>();
                             string sqlStrSelect = string.Empty;

                             for (int del = 0; del < dtDel.Rows.Count; del++)
                             {

                                 list.Add(new SqlParameter("@dJBookingNoteDtlID" + del.ToString(), dtDel.Rows[del]["PKID"].ToString()));
                                 sqlDelJob += "delete from BN_ShippingOrderDtl where BookingDtlID in(select PKID from BN_BookingDtl where BookingNoteDtlID=@dJBookingNoteDtlID" + del.ToString() + ");";
                                 sqlDelJob2 += "delete from BN_ShippingOrder where PKID in(select OrderID from BN_ShippingOrderDtl where BookingDtlID in(select PKID from BN_BookingDtl where BookingNoteDtlID=@dJBookingNoteDtlID" + del.ToString() + "));";

                                 DataTable dtbooking = bookingManage.GetBookingDtlByBookingNoteDtlID(int.Parse(dtDel.Rows[del]["PKID"].ToString()));
                                 if (dtbooking != null && dtbooking.Rows.Count > 0)//删除BookingDtl表里面的记录
                                 {
                                     for (int bo = 0; bo < dtbooking.Rows.Count; bo++)
                                     {
                                         list.Add(new SqlParameter("@dBPKID" + del.ToString() + bo.ToString(), dtbooking.Rows[bo]["PKID"].ToString()));
                                         sqlDelBooking += "delete from BN_BookingDtl where PKID=@dBPKID" + del.ToString() + bo.ToString() + ";";
                                         sqlDelBooking2 += "delete from BN_Booking where PKID in(select BookingID from BN_BookingDtl where PKID=@dBPKID" + del.ToString() + bo.ToString() +");";

                                        //获取工厂email

                                         // 读取工厂的联络人email
                                         sqlStrSelect = @"SELECT * 
                            FROM Sy_ClientLinkMan where PKID=(select VendorLinkMan from BN_BookingNoteDtl where PKID=(select BookingNoteDtlID from BN_BookingDtl where BookingNoteDtlID=@BookingNoteDtlIDs))";

                                         SqlParameter[] parmsSelect = new SqlParameter[1];
                                         DataTable dtEmail = new DataTable();

                                         parmsSelect[0] = new SqlParameter("@BookingNoteDtlIDs", dtbooking.Rows[bo]["BookingNoteDtlID"].ToString());
                                         dtEmail = db.RunSqlTab(sqlStrSelect, parmsSelect);
                                         if (dtEmail != null && dtEmail.Rows.Count > 0)
                                         {
                                             foreach (DataRow row in dtEmail.Rows)
                                             {
                                                 emailList.Add(row["Email"].ToString());
                                             }
                                         }

                                     }
                                 }

                                 sqlDelBookingNote += "delete from BN_BookingNoteDtl where PKID=@dJBookingNoteDtlID" + del.ToString() + ";";


                                 //判断该托运单是否已分配，如果已经分配了就发email到运输队
                                  string sqlJobS = "select * from BN_ShippingOrderDtl where BookingDtlID=(select PKID from BN_BookingDtl where BookingNoteDtlID=" + dtDel.Rows[del]["PKID"].ToString() + ")";
                                  DataTable dtJobS = new DataTable();
 
                                 dtJobS = db.RunSql(sqlJobS);

                                 if (dtJobS != null && dtJobS.Rows.Count > 0)//更新booking相关表时判断下Job该booking是否已分配job，如果已经分配了就发email到运输队
                                 {
                                     for (int i = 0; i < dtJobS.Rows.Count; i++)
                                     {
                                         //读取运输队的联络人email
                                         sqlStrSelect = @"select  * 
                                         FROM Sy_ClientLinkMan where ClientID=(select Contractor from BN_BookingDtl where PKID=
                                        (select BookingDtlID from BN_ShippingOrderDtl where PKID=@PKID))";

                                         SqlParameter[] parmsSelect = new SqlParameter[1];
                                         DataTable dtEmail = new DataTable();

                                         parmsSelect[0] = new SqlParameter("@PKID", dtJobS.Rows[i]["PKID"].ToString());
                                         dtEmail = db.RunSqlTab(sqlStrSelect, parmsSelect);
                                         if (dtEmail != null && dtEmail.Rows.Count > 0)
                                         {
                                             foreach (DataRow row in dtEmail.Rows)
                                             {
                                                 emailList.Add(row["Email"].ToString());
                                             }
                                         }
                                     }
                                 }


                                 //发email模板
                                 templeteDel += @"


[list]

     ";
                                 string dateFormat = "yyyy-MM-dd HH:mm:ss";
                                 string change = string.Empty;

                                 change = change + "ItemNO:" + dtDel.Rows[del]["ItemNO"].ToString() + @"

";
                                 change = change + "SONO:" + dtDel.Rows[del]["SONO"].ToString() + @"

";
                                 change = change + "PNNO:" + dtDel.Rows[del]["PNNO"].ToString() + @"

";
                                 change = change + "is delete by:" + Session["LoginID"].ToString() + @"

";

                                 templeteDel = templeteDel.Replace("[list]", change);


                                 foreach (string email in emailList)
                                 {
                                     if (StringUtil.IsEmailAddress(email))
                                     {
                                         //templete = templete.Replace("[title]", email);
                                         emailToDel += email + ",";
                                     }
                                 }
                                 if (emailToDel != string.Empty)
                                 {
                                     emailToDel = emailToDel.Substring(0, emailToDel.Length - 1) + ";";
                                 }
                                 templeteDel += "}";

                             }
                         }

                     }
                 }

                 else
                 {

                     List<string> emailList = new List<string>();
                     string sqlStrSelect = string.Empty;
                     sqlStrSelect =@"select * from BN_ShippingOrderDtl where BookingDtlID in(
                                    select PKID from BN_BookingDtl where BookingNoteDtlID in(
                                    select PKID from BN_BookingNoteDtl where BookingNoteID=@BookingNoteID))";
                     SqlParameter[] parmsSelect = new SqlParameter[1];
                     DataTable dtEmail = new DataTable();
                     parmsSelect[0] = new SqlParameter("@BookingNoteIDSel",Request["BookingNoteID"]);
                     DataTable dtSeldel = db.RunSqlTab(sqlStrSelect, parmsSelect);
                     if (dtSeldel != null && dtSeldel.Rows.Count > 0)//判断该托运单是否已经分配了job
                     {

                         for (int i = 0; i < dtSeldel.Rows.Count; i++)
                         {
                             //读取运输队的联络人email
                             sqlStrSelect = @"select  * 
                                         FROM Sy_ClientLinkMan where ClientID=(select Contractor from BN_BookingDtl where PKID=
                                        (select BookingDtlID from BN_ShippingOrderDtl where PKID=@PKID))";


                             parmsSelect[0] = new SqlParameter("@PKID", dtSeldel.Rows[i]["PKID"].ToString());
                             dtEmail = db.RunSqlTab(sqlStrSelect, parmsSelect);
                             if (dtEmail != null && dtEmail.Rows.Count > 0)
                             {
                                 foreach (DataRow row in dtEmail.Rows)
                                 {
                                     emailList.Add(row["Email"].ToString());
                                 }
                             }
                         }
                     }

                     //判断该托运单是否已经确认了booking

                     sqlStrSelect = @"select * from BookingDtl where BookingNoteDtlID in(
                                    select PKID from BN_BookingNoteDtl where BookingNoteID=@BookingNoteID))";
                     parmsSelect[0] = new SqlParameter("@BookingNoteID",Request["BookingNoteID"]);
                     DataTable dtBookingSeldel = db.RunSqlTab(sqlStrSelect, parmsSelect);
                     if (dtBookingSeldel != null && dtBookingSeldel.Rows.Count > 0)
                     {
                         for (int i = 0; i < dtBookingSeldel.Rows.Count; i++)
                         {                            
                                 //读取运输队的联络人email
                                 sqlStrSelect = @"select  * 
                                         FROM Sy_ClientLinkMan where ClientID=(select Contractor from BN_BookingDtl where PKID=
                                        (select BookingDtlID from BN_ShippingOrderDtl where PKID=@PKID))";

                                 parmsSelect[0] = new SqlParameter("@PKID", dtBookingSeldel.Rows[i]["PKID"].ToString());
                                 dtEmail = db.RunSqlTab(sqlStrSelect, parmsSelect);
                                 if (dtEmail != null && dtEmail.Rows.Count > 0)
                                 {
                                     foreach (DataRow row in dtEmail.Rows)
                                     {
                                         emailList.Add(row["Email"].ToString());
                                     }
                                 }                            
                         }
                     }

                     BN_BookingNoteQuery query = bookingNoteManage.GetBookingNoteByPKID(int.Parse(Request["BookingNoteID"]));


                     //发email模板
                     templeteDel += @"


[list]

     ";
                     string dateFormat = "yyyy-MM-dd HH:mm:ss";
                     string change = string.Empty;

                     change = change + "InvoiceNO:" + query.InvoiceNO + @"

";
         
                     change = change + "is delete by:" + Session["LoginID"].ToString() + @"

";

                     templeteDel = templeteDel.Replace("[list]", change);


                     foreach (string email in emailList)
                     {
                         if (StringUtil.IsEmailAddress(email))
                         {
                             //templete = templete.Replace("[title]", email);
                             emailToDel += email + ",";
                         }
                     }
                     if (emailToDel != string.Empty)
                     {
                         emailToDel = emailToDel.Substring(0, emailToDel.Length - 1) + ";";
                     }
                     templeteDel += "}";


                    // list.Add(new SqlParameter("@BookingNoteID",Request["BookingNoteID"]));
                     sqlDelJob += " delete from BN_ShippingOrderDtl where BookingDtlID in(select PKID from BN_BookingDtl where BookingNoteDtlID in(select PKID from BN_BookingNoteDtl where BookingNoteID=@BookingNoteID));";
                     sqlDelJob2 += " delete from BN_ShippingOrder where PKID in(select OrderID from BN_ShippingOrderDtl where BookingDtlID in(select PKID from BN_BookingDtl where BookingNoteDtlID in(select PKID from BN_BookingNoteDtl where BookingNoteID=@BookingNoteID)));";

                     sqlDelBooking += "delete from BN_BookingDtl where BookingNoteDtlID in(select PKID from BN_BookingNoteDtl where BookingNoteID=@BookingNoteID);";

                     sqlDelBooking2 += "delete from BN_Booking where PKID in(select BookingID from BN_BookingDtl where BookingNoteDtlID in(select PKID from BN_BookingNoteDtl where BookingNoteID=@BookingNoteID));";

                     sqlDelBookingNote += "delete from BN_BookingNoteDtl where BookingNoteID=@BookingNoteID;";


                 }

              parms = list.ToArray();

                 try
                 {
                     if (sqlBooking != string.Empty)
                     {
                         sqlStr += sqlBooking + sqlBookingDtl;
                     }
                     if (sqlJob != string.Empty)
                     {
                         sqlStr += sqlJob + sqlJobDtl;
                     }

                     if (sqlDelJob != string.Empty)
                     {
                         sqlStr += sqlDelJob2 + sqlDelJob;
                     }


                     if (sqlDelBooking != string.Empty)
                     {
                         sqlStr += sqlDelBooking2 + sqlDelBooking;
                     }

                     if (sqlDelBookingNote != string.Empty)
                     {
                         sqlStr += sqlDelBookingNote;
                     }
                 

                     if (bookingNoteManage.BookingNoteAdd(sqlStr, parms))
                     {

                         if (templete != string.Empty && emailTo != string.Empty)
                         {

                             string[] temps = templete.Substring(0, templete.Length - 1).Split(new char[] { '}' });
                             string[] emails = emailTo.Substring(0, emailTo.Length - 1).Split(new char[] { ';' });
                             for (int i = 0; i < temps.Length; i++)
                             {
                                 if (i < emails.Length)
                                 {
                                     string[] ems = emails[i].Split(new char[] { ',' });
                                     //string subject = "reminds from special-line!";
                                     //for (int j = 0; j < ems.Length; j++)
                                     //{
                                     //    SendMail send = new SendMail();
                                     //    string content = temps[i].Replace("[title]", ems[j]);
                                     //    send.MailBody = content;
                                     //    send.MailSubject = subject;
                                     //    send.MailTo = ems[j];

                                     //    send.Send();
                                     //}
                                     ISyAutoSendEmail autoEmail = new SyAutoSendEmail();
                                     autoEmail.InsertEmailContent("Update Shipping Order", temps[i], ems, int.Parse(Session["UserID"].ToString()));
                                 }
                             }
                         }


                         if (templeteUp != string.Empty && emailToUp != string.Empty)
                         {

                             string[] temps = templeteUp.Substring(0, templeteUp.Length - 1).Split(new char[] { '}' });
                             string[] emails = emailToUp.Substring(0, emailToUp.Length - 1).Split(new char[] { ';' });
                             for (int i = 0; i < temps.Length; i++)
                             {
                                 if (i < emails.Length)
                                 {
                                     string[] ems = emails[i].Split(new char[] { ',' });
                                     //string subject = "reminds from special-line!";
                                     //for (int j = 0; j < ems.Length; j++)
                                     //{
                                     //    SendMail send = new SendMail();
                                     //    string content = temps[i].Replace("[title]", ems[j]);
                                     //    send.MailBody = content;
                                     //    send.MailSubject = subject;
                                     //    send.MailTo = ems[j];

                                     //    send.Send();
                                     //}
                                     ISyAutoSendEmail autoEmail = new SyAutoSendEmail();
                                     autoEmail.InsertEmailContent("Update Shipping Order", temps[i], ems, int.Parse(Session["UserID"].ToString()));
                                 }
                             }
                         }

                         if (templeteDel != string.Empty && emailToDel != string.Empty)
                         {

                             string[] temps = templeteDel.Substring(0, templeteDel.Length - 1).Split(new char[] { '}' });
                             string[] emails = emailToDel.Substring(0, emailToDel.Length - 1).Split(new char[] { ';' });
                             for (int i = 0; i < temps.Length; i++)
                             {
                                 if (i < emails.Length)
                                 {
                                     string[] ems = emails[i].Split(new char[] { ',' });
                                     //string subject = "reminds from special-line!";
                                     //for (int j = 0; j < ems.Length; j++)
                                     //{
                                     //    SendMail send = new SendMail();
                                     //    string content = temps[i].Replace("[title]", ems[j]);
                                     //    send.MailBody = content;
                                     //    send.MailSubject = subject;
                                     //    send.MailTo = ems[j];

                                     //   send.Send();
                                     //}
                                     //TimeTask task = new TimeTask();
                                     //task.InsertEmailContent("Delete Shipping Order", temps[i], ems, int.Parse(Session["UserID"].ToString()));
                                     ISyAutoSendEmail autoEmail = new SyAutoSendEmail();
                                     autoEmail.InsertEmailContent("Delete Shipping Order", temps[i], ems, int.Parse(Session["UserID"].ToString()));
                                 }
                             }
                         }

                         Jscript.AlertAndRedirect(Resources.Messages.UpdateSuccess, "BookingNoteList.aspx", this.Page);
                     }
                 }
                 catch
                 {
                 }
         }

           
     }

    }
    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("BookingNoteList.aspx");
    }

    private void BindShipperLM(int clientID)
    {

        SqlParameter[] parms = new SqlParameter[1];
        parms[0] = new SqlParameter("@ClientID", clientID.ToString());
        string sqlStr = "select * from Sy_ClientLinkMan where ClientID =@ClientID";
        DataTable dt = clientManage.GetClientLinkManList(sqlStr, parms);
        ddlShipperLM.DataSource = dt;
        ddlShipperLM.DataTextField = "LinkMan";
        ddlShipperLM.DataValueField = "PKID";
        ddlShipperLM.DataBind();
        ddlShipperLM.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));

    }

    private void BindVendorLM(int clientID)
    {
       
        SqlParameter[] parms = new SqlParameter[1];
        parms[0] = new SqlParameter("@ClientID", clientID.ToString());
        string sqlStr = "select * from Sy_ClientLinkMan where ClientID =@ClientID";
        DataTable dt = clientManage.GetClientLinkManList(sqlStr, parms);
        ddlVendorLM.DataSource = dt;
        ddlVendorLM.DataTextField = "LinkMan";
        ddlVendorLM.DataValueField = "PKID";
        ddlVendorLM.DataBind();
        ddlVendorLM.Items.Insert(0, new ListItem(Resources.Messages.PleaseSelect, "0"));

    }

   

    protected void ddlShipper_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlShipper.SelectedValue != "0")
        {
            ddlShipperLM.Enabled = true;
        }
        else
        {
            ddlShipperLM.Enabled = false;
        }
        ddlShipperLM.Items.Clear();
        BindShipperLM(int.Parse(ddlShipper.SelectedValue));
    }

    private string GetClientName(int id)
    {
        return systemManage.GetClient(id);
    }


    protected void btnUpdateD_Click(object sender, EventArgs e)
    {
        if (Request["chkSelected"] != null)
        {
            ClearSelect();

            BN_BookingNoteQuery bnQuery = bookingNoteManage.GetBookingNoteByPKID(int.Parse(Request["BookingNoteID"]));
            if (bnQuery != null)
            {
                //if (bnQuery.Status == int.Parse(Enums.BookingNoteStatus.CHECK.ToString("d")))
                //{
                //    Jscript.AlertInAjax(Resources.Messages.BookingnoteNotEdit, UpdatePanel1);
                //    return;
                //}
            }

            string[] req = Request["chkSelected"].Split(new char[] { ',' });
            int gnum = 0;
            int pkid = 0;

            if (req.Length > 0)
            {
                gnum = int.Parse(req[0]);
                pkid = int.Parse(req[1]);
            }

            BN_BookingNoteDtlQuery bnDQuery = bookingNoteManage.GetBookingNoteDetailByID(pkid);

            if (bnDQuery != null)//是数据表里的数据
            {
                //if (!(bnDQuery.Status == int.Parse(Enums.BookingNoteDtlStatus.NEW.ToString("d")) || bnDQuery.Status == int.Parse(Enums.BookingNoteDtlStatus.CANCELBOOKING.ToString("d"))))
                //{
                //    Jscript.AlertInAjax(Resources.Messages.BookingnoteDtlNotEdit, UpdatePanel1);
                //    return;
                //}
            }

            DataTable dt = new DataTable();

            dt = (DataTable)ViewState["BookingNoteDetail"];

            txtConfirmNo.Text = dt.Rows[(gnum - 1)]["ConfirmNo"].ToString();
            ddlVendor.SelectedValue = dt.Rows[(gnum - 1)]["VendorID"].ToString();
            ddlWhouse.SelectedValue = dt.Rows[(gnum - 1)]["WhouseID"].ToString();
            txtSONO.Text = dt.Rows[(gnum - 1)]["SONO"].ToString();
            ddlFCLLCL.SelectedValue = dt.Rows[(gnum - 1)]["FCLLCL"].ToString();
            ddlHKPRC.SelectedValue = dt.Rows[(gnum - 1)]["HKPRC"].ToString();
           // txtJobDate.Text = dt.Rows[(gnum - 1)]["JobDate"].ToString();
            //txtDeliveryDate.Text = dt.Rows[(gnum - 1)]["DeliveryDate"].ToString();
                        
            if (dt.Rows[(gnum - 1)]["JobDate"].ToString() != string.Empty)
            {
                txtJobDate.Text = Convert.ToDateTime(dt.Rows[(gnum - 1)]["JobDate"].ToString()).ToString("yyyy-MM-dd");

                if (dt.Rows[(gnum - 1)]["JobDate"].ToString().Substring(11, 5) != "00:00")
                {
                    txtJobDateH.Text = dt.Rows[(gnum - 1)]["JobDate"].ToString().Substring(11, 5).Remove(2, 1).Trim();
                }
            }


            txtItemNO.Text = dt.Rows[(gnum - 1)]["ItemNO"].ToString();
            
            txtPCS.Text = int.Parse(dt.Rows[(gnum - 1)]["PCS"].ToString())!=0? dt.Rows[(gnum - 1)]["PCS"].ToString() : string.Empty;
            txtCTN.Text = int.Parse(dt.Rows[(gnum - 1)]["CTN"].ToString()) !=0?dt.Rows[(gnum - 1)]["CTN"].ToString() :string.Empty;
            txtGrossWT.Text = float.Parse(dt.Rows[(gnum - 1)]["GrossWT"].ToString()) != 0?dt.Rows[(gnum - 1)]["GrossWT"].ToString():string.Empty;
            txtVOL.Text = float.Parse(dt.Rows[(gnum - 1)]["VOL"].ToString()) != 0 ? dt.Rows[(gnum - 1)]["VOL"].ToString() : string.Empty;
            txtContainerNO.Text = dt.Rows[(gnum - 1)]["ContainerNO"].ToString();
            txtSealNO.Text = dt.Rows[(gnum - 1)]["SealNO"].ToString();
            //txtVVD.Text = dt.Rows[(gnum - 1)]["VV"].ToString();
            txtPNNO.Text = dt.Rows[(gnum - 1)]["PNNO"].ToString();
            //  txtBuyerPONO.Text = dt.Rows[(num - 1)]["BuyerPONO"].ToString();
            txtPCNOD.Text = dt.Rows[(gnum - 1)]["PCNO"].ToString();
            txtCargoReadyDate.Text = dt.Rows[(gnum - 1)]["CargoReadyDate"].ToString();
            //txtTruckCO.Text = dt.Rows[(gnum - 1)]["TruckCO"].ToString();
            txtRemarkD.Text = dt.Rows[(gnum - 1)]["Remark"].ToString();
           // txtBespokeDate.Text = dt.Rows[(gnum - 1)]["BespokeDate"].ToString();


            int id = 0;
            int.TryParse(ddlVendor.SelectedValue, out id);
            ddlVendorLM.Items.Clear();
            BindVendorLM(id);
            if (ddlVendorLM.Items.Count > 2)
            {
                ddlVendorLM.SelectedValue = dt.Rows[(gnum - 1)]["VendorLinkMan"].ToString() != string.Empty ? dt.Rows[(gnum - 1)]["VendorLinkMan"].ToString() : "0";
            }
            ddlVendorLM.Enabled = true;

            txtAppointmentNO.Text = dt.Rows[(gnum - 1)]["AppointmentNO"].ToString();

            num = int.Parse(dt.Rows[(gnum - 1)]["RowNum"].ToString());//给一个静态变量付值。更新哪条数据

        }
        else
        {
            Jscript.AlertInAjax(Resources.Messages.PleaseSelect, UpdatePanel2);

        }

    }
    protected void btnCopyD_Click(object sender, EventArgs e)
    {
        if (Request["chkSelected"] != null)
        {
            ClearSelect();

            BN_BookingNoteQuery bnQuery = bookingNoteManage.GetBookingNoteByPKID(int.Parse(Request["BookingNoteID"]));
            if (bnQuery != null)
            {
                //if (bnQuery.Status == int.Parse(Enums.BookingNoteStatus.CHECK.ToString("d")))
                //{
                //    Jscript.AlertInAjax(Resources.Messages.BookingnoteNotEdit, UpdatePanel1);
                //    return;
                //}
            }

            string[] req = Request["chkSelected"].Split(new char[] { ',' });
            int gnum = 0;
            int pkid = 0;

            if (req.Length > 0)
            {
                gnum = int.Parse(req[0]);
                pkid = int.Parse(req[1]);
            }

            BN_BookingNoteDtlQuery bnDQuery = bookingNoteManage.GetBookingNoteDetailByID(pkid);

            if (bnDQuery != null)//是数据表里的数据
            {
                //if (!(bnDQuery.Status == int.Parse(Enums.BookingNoteDtlStatus.NEW.ToString("d")) || bnDQuery.Status == int.Parse(Enums.BookingNoteDtlStatus.CANCELBOOKING.ToString("d"))))
                //{
                //    Jscript.AlertInAjax(Resources.Messages.BookingnoteDtlNotEdit, UpdatePanel1);
                //    return;
                //}
            }

            DataTable dt = new DataTable();

            dt = (DataTable)ViewState["BookingNoteDetail"];

            txtConfirmNo.Text = dt.Rows[(gnum - 1)]["ConfirmNo"].ToString();
            ddlVendor.SelectedValue = dt.Rows[(gnum - 1)]["VendorID"].ToString();
            ddlWhouse.SelectedValue = dt.Rows[(gnum - 1)]["WhouseID"].ToString();
            txtSONO.Text = dt.Rows[(gnum - 1)]["SONO"].ToString();
            ddlFCLLCL.SelectedValue = dt.Rows[(gnum - 1)]["FCLLCL"].ToString();
            ddlHKPRC.SelectedValue = dt.Rows[(gnum - 1)]["HKPRC"].ToString();

            if (dt.Rows[(gnum - 1)]["JobDate"].ToString() != string.Empty)
            {
                txtJobDate.Text = Convert.ToDateTime(dt.Rows[(gnum - 1)]["JobDate"].ToString()).ToString("yyyy-MM-dd");

                if (dt.Rows[(gnum - 1)]["JobDate"].ToString().Substring(11, 5) != "00:00")
                {
                    txtJobDateH.Text = dt.Rows[(gnum - 1)]["JobDate"].ToString().Substring(11, 5).Remove(2, 1).Trim();
                }
            }
           // txtDeliveryDate.Text = dt.Rows[(gnum - 1)]["DeliveryDate"].ToString();
            txtItemNO.Text = dt.Rows[(gnum - 1)]["ItemNO"].ToString();
            txtPCS.Text = int.Parse(dt.Rows[(gnum - 1)]["PCS"].ToString()) != 0 ? dt.Rows[(gnum - 1)]["PCS"].ToString() : string.Empty;
            txtCTN.Text = int.Parse(dt.Rows[(gnum - 1)]["CTN"].ToString()) != 0 ? dt.Rows[(gnum - 1)]["CTN"].ToString() : string.Empty;
            txtGrossWT.Text = float.Parse(dt.Rows[(gnum - 1)]["GrossWT"].ToString()) != 0 ? dt.Rows[(gnum - 1)]["GrossWT"].ToString() : string.Empty;
            txtVOL.Text = float.Parse(dt.Rows[(gnum - 1)]["VOL"].ToString()) != 0 ? dt.Rows[(gnum - 1)]["VOL"].ToString() : string.Empty;
            txtContainerNO.Text = dt.Rows[(gnum - 1)]["ContainerNO"].ToString();
            txtSealNO.Text = dt.Rows[(gnum - 1)]["SealNO"].ToString();
           // txtVVD.Text = dt.Rows[(gnum - 1)]["VV"].ToString();
            txtPNNO.Text = dt.Rows[(gnum - 1)]["PNNO"].ToString();
            //  txtBuyerPONO.Text = dt.Rows[(num - 1)]["BuyerPONO"].ToString();
            txtPCNOD.Text = dt.Rows[(gnum - 1)]["PCNO"].ToString();
            txtCargoReadyDate.Text = dt.Rows[(gnum - 1)]["CargoReadyDate"].ToString();
            //txtTruckCO.Text = dt.Rows[(gnum - 1)]["TruckCO"].ToString();
            txtRemarkD.Text = dt.Rows[(gnum - 1)]["Remark"].ToString();
            //txtBespokeDate.Text = dt.Rows[(gnum - 1)]["BespokeDate"].ToString();

            int id = 0;
            int.TryParse(ddlVendor.SelectedValue, out id);
            ddlVendorLM.Items.Clear();
            BindVendorLM(id);
            ddlVendorLM.SelectedValue = dt.Rows[(gnum - 1)]["VendorLinkMan"].ToString() != string.Empty ? dt.Rows[(gnum - 1)]["VendorLinkMan"].ToString() : "0";
            ddlVendorLM.Enabled = true;

            //txtSourceCode.Text = dt.Rows[(gnum - 1)]["SourceCode"].ToString();
            txtAppointmentNO.Text = dt.Rows[(gnum - 1)]["AppointmentNO"].ToString();

            num = -1; //给一个静态变量付值。更新哪条数据

        }
        else
        {
            Jscript.AlertInAjax(Resources.Messages.PleaseSelect, UpdatePanel2);
        }
    }
    protected void btnDelD_Click(object sender, EventArgs e)
    {
        if (Request["chkSelected"] != null)
        {
            BN_BookingNoteQuery bnQuery = bookingNoteManage.GetBookingNoteByPKID(int.Parse(Request["BookingNoteID"]));
            if (bnQuery != null)
            {
                //if (bnQuery.Status == int.Parse(Enums.BookingNoteStatus.CHECK.ToString("d")))
                //{
                //    Jscript.AlertInAjax(Resources.Messages.BookingnoteNotEdit, UpdatePanel1);
                //    return;
                //}
            }

            string[] req = Request["chkSelected"].Split(new char[] { ',' });
            int gnum = 0;
            int pkid = 0;

            if (req.Length > 0)
            {
                gnum = int.Parse(req[0]);
                pkid = int.Parse(req[1]);
            }

            BN_BookingNoteDtlQuery bnDQuery = bookingNoteManage.GetBookingNoteDetailByID(pkid);

            if (bnDQuery != null)//是数据表里的数据
            {
                //if (!(bnDQuery.Status == int.Parse(Enums.BookingNoteDtlStatus.NEW.ToString("d")) || bnDQuery.Status == int.Parse(Enums.BookingNoteDtlStatus.CANCELBOOKING.ToString("d"))))
                //{
                //    Jscript.AlertInAjax(Resources.Messages.BookingnoteDtlNotEdit, UpdatePanel1);
                //    return;
                //}
            }

            DataTable dt = new DataTable();

            dt = (DataTable)ViewState["BookingNoteDetail"];

            dt.Rows.RemoveAt((gnum - 1));
            isUpdate = true;
            dataBindDetail();

        }
        else
        {
            Jscript.AlertInAjax(Resources.Messages.PleaseSelect, UpdatePanel2);
        }
    }

    protected void ddlVendor_SelectedIndexChanged(object sender, EventArgs e)
    {

        if (ddlVendor.SelectedValue != "0")
        {
            ddlVendorLM.Enabled = true;
        }
        else
        {
            ddlVendorLM.Enabled = false;
        }
        ddlVendorLM.Items.Clear();
        BindVendorLM(int.Parse(ddlVendor.SelectedValue));

    }
}
